// pages/member/cart/index.js
var t = getApp(),
  a = t.requirejs("check"),
  e = t.requirejs("core");
Page({
  data: {
    route: "member_cart",
    menu: t.tabBar,
    menu_show: false,
    icons: t.requirejs("icons"),
    show:false,
    edit_list: [],
    list:[],
    edit:false,  //默认结算页面
   // editcheckall:!1
    merch_list: !1,
    ischeckall:true,
    member_change:true,
    delBtnWidth: 160,//删除按钮宽度单位（rpx）
    config:t.config
  },
  //底部导航跳转
  menu_url: function (k) {
    e.menu_url(k, 2);
  },
 
  onLoad: function (options) {
    e.compatible_phonex(this);
    e.ReName(getApp().config.gou+'物车');
    var that=this;
    if (options != null && options != undefined) {
      that.setData({
        tabbar_index: options.tabbar_index ? options.tabbar_index : -1
      });
    }
    e.setting();
    // 页面初始化 options为页面跳转所带来的参数
    that.initEleWidth();
   // this.get_cart();
    that.setData({
      menu: getApp().tabBar,
      config: getApp().config
    })

    that.get_cart()
  },
/**
     * 滑动删除页面效果
  */
  touchS: function (e) {
    if (e.touches.length == 1) {
      this.setData({
        //设置触摸起始点水平方向位置
        startX: e.touches[0].clientX
      });
    }
  },
  touchM: function (e) {
    if (e.touches.length == 1) {
      //手指移动时水平方向位置
      var moveX = e.touches[0].clientX;
      //手指起始点位置与移动期间的差值
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var txtStyle = "";
      if (disX == 0 || disX < 0) {//如果移动距离小于等于0，文本层位置不变
        txtStyle = "left:0px";
      } else if (disX > 0) {//移动距离大于0，文本层left值等于手指移动距离
        txtStyle = "left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度
          txtStyle = "left:-" + delBtnWidth + "px";
        }
      }
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = this.data.list;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        list: list
      });
    }
  },
  touchE: function (e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = this.data.list;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        list: list
      });
    }
  },
  //获取元素自适应后的实际宽度
  getEleWidth: function (w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2);//以宽度750px设计稿做宽度的自适应
      // console.log(scale);
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
      // Do something when catch error
    }
  },
  initEleWidth: function () {
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  },
  //点击删除按钮事件
  delItem: function (i) {
   
    var that=this,
      cart_id = e.data(i).id; //获取列表中要删除项的cart_id
    e.confirm("是否确认删除该商品?", function () {
      e.get("Cart/DelCart", {
        cart_id: cart_id
      }, function (t) {

        0 == t.code ? (
          e.success('删除成功'),
          setTimeout(function(){
            that.setData({
              edit: false
            }),
              that.get_cart()
          },1e3)
         
        ) : (e.alert(t.msg))


      });
    })
    
  },
  onShow: function () {
    
   
  },
  /**
  * 下拉刷新
  */
  onPullDownRefresh: function () {
    this.get_cart()
    wx.stopPullDownRefresh();
  },
  /**
     * 商品列表
     * @param uid 用户id
     * @return array
     */
  get_cart: function () {
    var a,
      s = {},
      i = this;
    e.get("Cart/cart", { uid: getApp().getCache("userinfo").uid}, function (e) {
      e.info.forEach(function (t) {
        t.txtStyle=""
      })
     if(e.info.length == 0){
       i.setData({empty:1})
     } else { i.setData({ empty: !1 })}
     
     //每个商品默认选中
     for (var c in e.info) {
       s[e.info[c].cart_id] = true
     }
      a = {
        show: true,//隐藏loading
        checkObj: s,//每个商品默认选中状态
        ischeckall: true,//全选
        list : e.info || [],
        checkNum:e.info.length
      },
       i.setData(a)
      i.caculate()
    },true)
  },
  /**
   *计算购物车商品总数量，总金额
   * @param this.data.list
   * @return string
   */

  caculate: function(){
    var t=this,
    order_money=0,
    total = 0,
    s = t.data.checkObj,
    d=t.data.list;
    d.forEach(function (a) {
       if (s[a.cart_id] && a.sku) { 
          total += a.num;
         order_money += parseFloat(a.num * a.sku.price);
          } 
    })
    
   t.setData({
     order_money: parseFloat(order_money).toFixed(2),
     total: total
   })
  },

  /**
   *购物车单个商品加减数量
   * @param cart_id
   * @param num 数量改变值
   * @return array
   */
  number: function(t){
    var a = this,
      s = e.pdata(t),
      num=s.value,
      o = s.id;
  
    if (!t.target.dataset.action) {
      console.log(11)
        return false;
    }
    
    if (t.target.dataset.action == "minus"){
      if (num <= 1) {
        return false;
      }
      num = parseInt(num) - 1
    }
    if(t.target.dataset.action == "plus"){
      if (num >= s.max) {
        e.toast('最大购买量 ' + s.max + '件！')
        return false;
      }
      num = parseInt(num) + 1
    }
    e.post("Cart/cartNum", {
      cart_id: o,
      num: num,  //购买数量
    }, function (t) {
       if(t.code==0){
         a.get_cart()
       }
         
        
        
    })
  },

   /**
   *购物车商品全选
   * @param ischeckall
   * @return bool
   */
  checkAllClick: function (t) {
    var t = !this.data.ischeckall,
      e = this.data.checkObj,
      a = {
        ischeckall: t,
        checkObj: e
      };
    for (var i in e)
      a.checkObj[i] = t;
    a.checkNum = t ? this.data.list.length : 0,
      this.setData(a)
    this.caculate()
  },

  /**
   *购物车单个商品选择
   * @param goodsid
   * @param checkObj bool值
   * @return bool
   */
  itemClick: function (t) {
    var a = this,
      i = e.pdata(t).id,
      s = e.pdata(t).goodsid,
      c = a.data.checkObj,
        l = a.data.checkNum;
      c[i] ? (c[i] = false, l--) : (c[i] = true, l++);
      var o = true;
      for (var n in c)
        if (!c[n]) {
          o = false;
          break
        }//有一个未选中，则为非全选状态
      console.log(c)
      a.setData({
        checkObj: c,
        ischeckall: o,
        checkNum: l
      })
      a.caculate()
  },

  /**
   *购物车修改，删除,支付
   */
  edit: function (t) {
    var i,
      s = e.data(t),
      that = this;
    switch (s.action) {
      //修改
      case "edit":
        this.setData({
          edit: true
        });
        break;
        //完成
      case "complete":
          this.setData({
          edit: false
          });
        break;
        //移动到关注
      case "move":
          a.isObject(i) || e.post("member/cart/tofavorite", {
            ids: i
          }, function (t) {
            that.get_cart()
          });
        break;
        //删除
      case "delete":
        var s = that.data.checkObj,
          l = [];
        for (var c in s)
          s[c] && l.push(c);//push() 方法可把它的参数顺序添加到 arrayObject 的尾部
        if (l.length < 1)
          return;
        l = l.toString()
          e.confirm("是否确认删除该商品?", function () {
            e.post("Cart/DelCart", {
              cart_id: l
            }, function (t) {
              
                0 == t.code ? (
                  e.toast('删除成功'),
                  that.setData({
                    edit: false
                  }),
                  that.get_cart()
                ): e.alert(t.msg)

              
          });
          })
        break;
        //购买
      case "pay":
        var s = that.data.checkObj,
          d = that.data.list,
        l=[],
          k = [];
        d.forEach(function (a) {
          if (s[a.cart_id] && a.sku) {
            l.push(a.cart_id)
          }
        })
          //push() 方法可把它的参数顺序添加到 arrayObject 的尾部
        if (l.length < 1)
          return;
        l = l.toString()
          wx.navigateTo({
            url: "/yb_shop/pages/order/create/index?cart_id=" + l + "&uid=" + getApp().getCache("userinfo").uid+"&type=cart"
        })
    }
  },

  //分享
  onShareAppMessage: function () {
    return e.onShareAppMessage()
  }
})